package com.ruoyi.yipaiju.controller;

import com.google.common.collect.ImmutableMap;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.dict.SpiderHouseGrabStatus;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.common.utils.http.HttpRequest;
import com.ruoyi.common.utils.http.HttpRespons;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.yipaiju.domain.ForeclosedHouse;
import com.ruoyi.yipaiju.domain.ServerManage;
import com.ruoyi.yipaiju.domain.SpiderHouse;
import com.ruoyi.yipaiju.domain.StorageRelationship;
import com.ruoyi.yipaiju.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/spider")
public class SpiderController {

    private static final Logger logger = LoggerFactory.getLogger(SpiderController.class);

    @Autowired
    private IWechatService wechatService;
    @Autowired
    private IServerManageService serverManageService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISpiderHouseService spiderHouseService;
    @Autowired
    private IForeclosedHouseService foreclosedHouseService;
    @Autowired
    private IStorageRelationshipService storageRelationshipService;

    @Anonymous
    @GetMapping("/server/params")
    public ApiResult serverParams(HttpServletRequest request, @RequestParam(defaultValue = "") String lanSign)
    {
        String clientIp = StringUtils.isNotEmpty(lanSign) ? lanSign : IpUtils.getIpAddr(request);
        logger.info("客户端IP："+clientIp);
        // 根据ip获取到配置信息
        ServerManage serverManage = serverManageService.selectOneServerManage(Builder.of(ServerManage::new)
                .with(ServerManage::setServerIp, clientIp)
                .build());
        if (serverManage != null){
            serverManage.setRealIp(clientIp);
            return ApiResult.success(serverManage);
        }else {
            return ApiResult.success(ImmutableMap.of("realIp", clientIp));
        }
    }

    @Anonymous
    @GetMapping("/server/status")
    public ApiResult serverStatus(Integer status, HttpServletRequest request, @RequestParam(defaultValue = "") String lanSign)
    {
        String clientIp = StringUtils.isNotEmpty(lanSign) ? lanSign : IpUtils.getIpAddr(request);
        // 根据ip获取到配置信息
        ServerManage serverManage = serverManageService.selectOneServerManage(Builder.of(ServerManage::new)
                .with(ServerManage::setServerIp, clientIp)
                .build());
        if (serverManage != null){
            serverManage.setStatus(status);
            serverManageService.updateServerManage(serverManage);
            return ApiResult.success();
        }
        return ApiResult.error();
    }

    @Anonymous
    @GetMapping("/server/countadd")
    public ApiResult serverCountadd(HttpServletRequest request, @RequestParam(defaultValue = "") String lanSign)
    {
        String clientIp = StringUtils.isNotEmpty(lanSign) ? lanSign : IpUtils.getIpAddr(request);
        // 根据ip获取到配置信息
        ServerManage serverManage = serverManageService.selectOneServerManage(Builder.of(ServerManage::new)
                .with(ServerManage::setServerIp, clientIp)
                .build());
        if (serverManage != null){
            serverManage.setRunCount(((serverManage.getRunCount()==null?0:serverManage.getRunCount().intValue())+1));
            serverManageService.updateServerManage(serverManage);
            return ApiResult.success();
        }
        return ApiResult.error();
    }

    @Anonymous
    @GetMapping("/warn/notify")
    public ApiResult warnNotify(String type, HttpServletRequest request, @RequestParam(defaultValue = "") String lanSign)
    {
        String clientIp = StringUtils.isNotEmpty(lanSign) ? lanSign : IpUtils.getIpAddr(request);
        String ableKey = "constants:spider.wechat.warn.message.able:"+clientIp+"_"+type;
        // 判断调用频率
        Boolean msgAble = redisCache.getCacheObject(ableKey);
        if (msgAble != null && !msgAble.booleanValue()){
            return ApiResult.error();
        }
        redisCache.setCacheObject(ableKey, false, 10, TimeUnit.MINUTES);
        String template = "TrgmcPoBWrQvZEKwoVokC2R8JqUsAH2rPqhg9hKuEqw";
        String appid = configService.selectConfigByKey("biz.wechat.warn.appid");
        String secret = configService.selectConfigByKey("biz.wechat.warn.secret");
        String access_token = wechatService.getAccessToken(appid, secret);
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;

//        String openId = "oSYqO6ttbONJ6ks-IYKRLc02McB8";   // me
//        String openId1 = "oSYqO6qL6RzwGgudkrfN4AypL8Vc";  // 老何

        String openIds = configService.selectConfigByKey("biz.wechat.warn.openIds");
        if (StringUtils.isNotEmpty(openIds) && StringUtils.isNotEmpty(access_token)){
            for (String openId : openIds.split(",")) {
                String data = "{\n" +
                        "           \"touser\":\""+openId+"\",\n" +
                        "           \"template_id\":\""+template+"\",\n" +
                        "           \"url\":\"\",  \n" +
                        "           \"data\":{\n" +
                        "                   \"first\":{\n" +
                        "                       \"value\":\"爬虫告警\"\n" +
                        "                   },\n" +
                        "                   \"keyword1\":{\n" +
                        "                       \"value\":\"易拍居爬虫\"\n" +
                        "                   },\n" +
                        "                   \"keyword2\":{\n" +
                        "                       \"value\":\"人机模块\"\n" +
                        "                   },\n" +
                        "                   \"keyword3\": {\n" +
                        "                       \"value\":\""+ clientIp +"\"\n" +
                        "                   },\n" +
                        "                   \"keyword4\": {\n" +
                        "                       \"value\":\""+type+"\"\n" +
                        "                   },\n" +
                        "                   \"keyword5\": {\n" +
                        "                       \"value\":\""+ DateUtils.getTime() +"\"\n" +
                        "                   },\n" +
                        "                   \"remark\": {\n" +
                        "                       \"value\":\"请及时处理！\"\n" +
                        "                   }\n" +
                        "           }\n" +
                        "       }";


                HttpRequest httpRequest = new HttpRequest();
                HttpRespons httpRespons = httpRequest.sendPost(url, data);
                logger.info("模板消息发送结果："+httpRespons.getContent());
            }
            return ApiResult.success();
        }

        return ApiResult.error();

    }

    @Anonymous
    @GetMapping("/client/detailfail/{id}")
    public ApiResult clientDetailfail(@PathVariable("id") Long id, HttpServletRequest request, @RequestParam(defaultValue = "") String lanSign)
    {
        String clientIp = StringUtils.isNotEmpty(lanSign) ? lanSign : IpUtils.getIpAddr(request);
        SpiderHouse spiderHouse = spiderHouseService.selectSpiderHouseById(id);
        if (spiderHouse != null){
            spiderHouse.setGrabStatus(SpiderHouseGrabStatus.GRABFAIL.getValue());
            spiderHouse.setServerIp(clientIp);
            spiderHouseService.updateSpiderHouse(spiderHouse);
            return ApiResult.success();
        }
        return ApiResult.error();
    }

    @Anonymous
    @PostMapping("/client/list")
    public ApiResult clientList(HttpServletRequest request, @RequestBody ServerManage serverManage)
    {
        try {
            String clientIp = StringUtils.isNotEmpty(serverManage.getLanSign()) ? serverManage.getLanSign() : IpUtils.getIpAddr(request);
            return spiderHouseService.spiderHouseListHandle(serverManage, clientIp);
        }catch (Exception e){
            e.printStackTrace();
        }

        return ApiResult.error();
    }

    @Anonymous
    @PostMapping("/client/detail")
    public ApiResult clientSave(HttpServletRequest request, @RequestBody ForeclosedHouse foreclosedHouse)
    {
        try {
            String clientIp = StringUtils.isNotEmpty(foreclosedHouse.getLanSign()) ? foreclosedHouse.getLanSign() : IpUtils.getIpAddr(request);

            SpiderHouse spiderHouse = null;
            if (foreclosedHouse.getSpiderHouseId() != null){
                spiderHouse = spiderHouseService.selectSpiderHouseById(foreclosedHouse.getSpiderHouseId());
                if (spiderHouse != null){
                    spiderHouse.setGrabStatus(SpiderHouseGrabStatus.GRABFINISH.getValue());
                    spiderHouse.setGrabCount1(1);
                    spiderHouse.setFinishTime(new Date());
                    spiderHouse.setServerIp(clientIp);
                    spiderHouseService.updateSpiderHouse(spiderHouse);
                }
            }

            ForeclosedHouse foreclosedHouse1 = foreclosedHouseService.selectForeclosedHouseByCode(foreclosedHouse.getNameMd5());
            if (foreclosedHouse1 == null){
                spiderHouseCopyForeclosed(spiderHouse, foreclosedHouse);
                foreclosedHouseService.insertForeclosedHouse(foreclosedHouse);
            }else {
                // 更新
                foreclosedHouse.setId(foreclosedHouse1.getId());
                spiderHouseCopyForeclosed(spiderHouse, foreclosedHouse);
                foreclosedHouseService.updateForeclosedHouse(foreclosedHouse);
                if (StringUtils.isNotEmpty(foreclosedHouse1.getNameMd5())){
                    storageRelationshipService.deleteStorageRelationshipByCondition(Builder.of(StorageRelationship::new)
                            .with(StorageRelationship::setRelatedObjectId, foreclosedHouse1.getNameMd5())
                            .build());
                }
            }
            if (foreclosedHouse.getStorageRelationships() != null && foreclosedHouse.getStorageRelationships().size() > 0){
                storageRelationshipService.insertStorageRelationshipList(foreclosedHouse.getStorageRelationships());
            }

            if (StringUtils.isNotEmpty(foreclosedHouse.getAddress())){
                // TODO 根据地址处理小区数据

            }
            return ApiResult.success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return ApiResult.error();
    }

    public void spiderHouseCopyForeclosed(SpiderHouse spiderHouse, ForeclosedHouse foreclosedHouse){
        if (spiderHouse == null) return;
        if (spiderHouse.getHouseType() != null){
            foreclosedHouse.setHouseType(spiderHouse.getHouseType());
        }
        if (spiderHouse.getStatus() != null){
            foreclosedHouse.setStatus(spiderHouse.getStatus());
        }
        if (spiderHouse.getCurrentPrice() != null){
            // 以详情爬过来的为主 所以这里多加一个判断
            if (foreclosedHouse.getPriceYuan() == null){
                foreclosedHouse.setPriceYuan(spiderHouse.getCurrentPrice());
            }
            if (foreclosedHouse.getDealPrice() == null){
                foreclosedHouse.setDealPrice(spiderHouse.getCurrentPrice());
            }
            if (foreclosedHouse.getMarketPriceYuan() == null){
                foreclosedHouse.setMarketPriceYuan(spiderHouse.getCurrentPrice());
            }
        }
        if (spiderHouse.getDiscountRate() != null){
            foreclosedHouse.setDiscountRate(spiderHouse.getDiscountRate());
        }
        if (spiderHouse.getEnsurePrice() != null){
            foreclosedHouse.setDepositYuan(spiderHouse.getEnsurePrice());
        }
        if (spiderHouse.getMarketPrice() != null){
            foreclosedHouse.setMarketPriceYuan(spiderHouse.getMarketPrice());
        }
        // 抓到的评估价
        if (spiderHouse.getAssessmentPrice() != null){
            foreclosedHouse.setEstimatePriceYuan(spiderHouse.getAssessmentPrice());
        }
        // 没抓到就取市场价
        if (foreclosedHouse.getEstimatePriceYuan() == null){
            foreclosedHouse.setEstimatePriceYuan(foreclosedHouse.getMarketPriceYuan());
        }
        if (spiderHouse.getMinPrice() != null && spiderHouse.getMinPrice().longValue() > 0){
            foreclosedHouse.setPriceYuan(spiderHouse.getMinPrice());
        }
        // 以详情爬过来的为主 所以这里多加一个判断
        if (StringUtils.isNotEmpty(spiderHouse.getAddress()) && StringUtils.isEmpty(foreclosedHouse.getAddress())){
            foreclosedHouse.setAddress(spiderHouse.getAddress());
        }
        if (spiderHouse.getCourt() != null){
            foreclosedHouse.setCourt(spiderHouse.getCourt());
        }
        if (spiderHouse.getTitle() != null){
            foreclosedHouse.setTitle(spiderHouse.getTitle());
            foreclosedHouse.setResidentialQuarterName(spiderHouse.getTitle());
        }
        if (spiderHouse.getStartTime() != null){
            foreclosedHouse.setStartTime(spiderHouse.getStartTime());
        }
        if (spiderHouse.getEndTime() != null){
            foreclosedHouse.setEndTime(spiderHouse.getEndTime());
        }
        if (spiderHouse.getExt2() != null){
            foreclosedHouse.setBrowseCount(Integer.parseInt(spiderHouse.getExt2()));
        }
        if (foreclosedHouse.getUnitPriceYuan() == null) {
            if (foreclosedHouse.getBuiltUpAreaSquareCentimeter() != null && foreclosedHouse.getBuiltUpAreaSquareCentimeter().compareTo(new BigDecimal(0)) > 0){
                if (foreclosedHouse.getMarketPriceYuan() != null && foreclosedHouse.getMarketPriceYuan().intValue() > 0){
                    foreclosedHouse.setUnitPriceYuan(new BigDecimal(foreclosedHouse.getMarketPriceYuan()).divide(new BigDecimal(foreclosedHouse.getBuiltUpAreaSquareCentimeter().toString()), BigDecimal.ROUND_HALF_UP).intValue());
                }
            }
        }

        //折扣
        if (foreclosedHouse.getDiscountRate() == null){
            if (foreclosedHouse.getEstimatePriceYuan() != null && foreclosedHouse.getMarketPriceYuan() != null){
                foreclosedHouse.setDiscountRate(new BigDecimal(foreclosedHouse.getMarketPriceYuan()*10).divide(new BigDecimal(foreclosedHouse.getEstimatePriceYuan()), BigDecimal.ROUND_HALF_UP).setScale(2));
            }
        }

    }


    // TODO 这个是加判断不覆盖的 感觉不对  所以不用这个了
//    public void spiderHouseCopyForeclosed(SpiderHouse spiderHouse, ForeclosedHouse foreclosedHouse){
//        if (spiderHouse == null) return;
//        if (StringUtils.isNotEmpty(spiderHouse.getHouseType()) && StringUtils.isEmpty(foreclosedHouse.getHouseType())){
//            foreclosedHouse.setHouseType(spiderHouse.getHouseType());
//        }
//        if (StringUtils.isNotEmpty(spiderHouse.getStatus()) && StringUtils.isEmpty(foreclosedHouse.getStatus())){
//            foreclosedHouse.setStatus(spiderHouse.getStatus());
//        }
//        if (spiderHouse.getAssessmentPrice() != null && foreclosedHouse.getEstimatePriceYuan() == null){
//            foreclosedHouse.setEstimatePriceYuan(spiderHouse.getAssessmentPrice());
//        }
//        if (spiderHouse.getCurrentPrice() != null){
//            foreclosedHouse.setPriceYuan(spiderHouse.getCurrentPrice());
//            foreclosedHouse.setDealPrice(spiderHouse.getCurrentPrice());
//            foreclosedHouse.setMarketPriceYuan(spiderHouse.getCurrentPrice());
//        }
//        if (spiderHouse.getDiscountRate() != null && foreclosedHouse.getDiscountRate() == null){
//            foreclosedHouse.setDiscountRate(spiderHouse.getDiscountRate());
//        }
//        if (spiderHouse.getEnsurePrice() != null && foreclosedHouse.getDepositYuan() == null){
//            foreclosedHouse.setDepositYuan(spiderHouse.getEnsurePrice());
//        }
//        if (spiderHouse.getMarketPrice() != null && foreclosedHouse.getMarketPriceYuan() == null){
//            foreclosedHouse.setMarketPriceYuan(spiderHouse.getMarketPrice());
//        }
//        if (spiderHouse.getMinPrice() != null && foreclosedHouse.getPriceYuan() == null){
//            foreclosedHouse.setPriceYuan(spiderHouse.getMinPrice());
//        }
//        if (StringUtils.isNotEmpty(spiderHouse.getAddress()) && StringUtils.isEmpty(foreclosedHouse.getAddress())){
//            foreclosedHouse.setAddress(spiderHouse.getAddress());
//        }
//        if (StringUtils.isNotEmpty(spiderHouse.getCourt()) && StringUtils.isEmpty(foreclosedHouse.getCourt())){
//            foreclosedHouse.setCourt(spiderHouse.getCourt());
//        }
//        if (StringUtils.isNotEmpty(spiderHouse.getTitle()) && StringUtils.isEmpty(foreclosedHouse.getTitle())){
//            foreclosedHouse.setTitle(spiderHouse.getTitle());
//            foreclosedHouse.setResidentialQuarterName(spiderHouse.getTitle());
//        }
//        if (spiderHouse.getStartTime() != null && foreclosedHouse.getStartTime() == null){
//            foreclosedHouse.setStartTime(spiderHouse.getStartTime());
//        }
//        if (spiderHouse.getEndTime() != null && foreclosedHouse.getEndTime() == null){
//            foreclosedHouse.setEndTime(spiderHouse.getEndTime());
//        }
//        if (foreclosedHouse.getUnitPriceYuan() == null) {
//            if (foreclosedHouse.getBuiltUpAreaSquareCentimeter() != null && foreclosedHouse.getBuiltUpAreaSquareCentimeter().compareTo(new BigDecimal(0)) > 0){
//                if (foreclosedHouse.getMarketPriceYuan() != null && foreclosedHouse.getMarketPriceYuan().intValue() > 0){
//                    foreclosedHouse.setUnitPriceYuan(new BigDecimal(foreclosedHouse.getMarketPriceYuan()).divide(new BigDecimal(foreclosedHouse.getBuiltUpAreaSquareCentimeter().toString()), BigDecimal.ROUND_HALF_UP).intValue());
//                }
//            }
//        }
//    }


    public static void main(String[] args) {
//        String a = "https://api.m.jd.com/api?appid=paimai&functionId=paimai_unifiedSearch&body=%7B%22investmentType%22%3A%22%22%2C%22apiType%22%3A12%2C%22page%22%3A1%2C%22pageSize%22%3A40%2C%22keyword%22%3A%22%22%2C%22provinceId%22%3A%22%22%2C%22cityId%22%3A%22%22%2C%22countyId%22%3A%22%22%2C%22multiPaimaiStatus%22%3A%22%22%2C%22multiDisplayStatus%22%3A%22%22%2C%22multiPaimaiTimes%22%3A%22%22%2C%22childrenCateId%22%3A%22101%2C102%2C103%2C104%22%2C%22currentPriceRangeStart%22%3A%22%22%2C%22currentPriceRangeEnd%22%3A%22%22%2C%22timeRangeTime%22%3A%22endTime%22%2C%22timeRangeStart%22%3A%22%22%2C%22timeRangeEnd%22%3A%22%22%2C%22loan%22%3A%22%22%2C%22purchaseRestriction%22%3A%22%22%2C%22orgId%22%3A%22%22%2C%22orgType%22%3A%22%22%2C%22sortField%22%3A8%2C%22projectType%22%3A1%2C%22reqSource%22%3A0%2C%22labelSet%22%3A%22%22%2C%22publishSource%22%3A%22%22%7D&clientVersion=paimai-h5-1.0.0&client=paimai-h5&t=1688093465907&h5st=20230630105105935%3B0039417993556085%3B106e8%3Btk03waed61c0918nt1IboQ7WNUPnqswcfOWhh18jSkgH73gg5ashT8MNJnW36wOUmXZOM9MQH4nTNw7WCRYVYRqw7g-w%3B26bc279e2d5c048e445327476a6c3aa21d19d7dfbd7afef4cf09fe5e5bd96d2f%3B3.1%3B1688093465935%3B24c9ee85e67cf80746dd82817ecbeafc7a829b35c7f446a4c7d476cc9faa1d8834a93323ad7bce9bef1bba682b93d2e3938e6fdf0b116e62557e4895c51d3caa8f37f0f43c683675e058de07d25d6a4ac2f7032fdaa2bd23286ee4fe08a60cdb&x-api-eid-token=jdd03N6BR43SWR4ULH2PLEEWIT7KVASJAAZAKOLRMGMD3NCZVDMVHWXIXJ6DPUFRP2RH2KHA3Q4QSS6ODNURRP3KM7W6LXQAAAAMJBIPKSCAAAAAACOA424NLSE7PYIX";
//
//
//        String body = "{\"investmentType\":\"\",\"apiType\":12,\"page\":1,\"pageSize\":40,\"keyword\":\"\",\"provinceId\":\"\",\"cityId\":\"\",\"countyId\":\"\",\"multiPaimaiStatus\":\"\",\"multiDisplayStatus\":\"\",\"multiPaimaiTimes\":\"\",\"childrenCateId\":\"101,102,103,104\",\"currentPriceRangeStart\":\"\",\"currentPriceRangeEnd\":\"\",\"timeRangeTime\":\"endTime\",\"timeRangeStart\":\"\",\"timeRangeEnd\":\"\",\"loan\":\"\",\"purchaseRestriction\":\"\",\"orgId\":\"\",\"orgType\":\"\",\"sortField\":8,\"projectType\":1,\"reqSource\":0,\"labelSet\":\"\",\"publishSource\":\"\"}";
//
//        try {
//            System.out.println(URLDecoder.decode(a, "utf-8"));
//
//
//            System.out.println(body);
//        }catch (Exception e){
//
//        }

//        HttpRequest httpRequest = new HttpRequest();
//        HttpRespons httpRespons = httpRequest.sendGet(a);
//        System.out.println(httpRespons.getContent());

//        BigDecimal bigDecimal = new BigDecimal(1000000 * 10).divide(new BigDecimal(1200000), BigDecimal.ROUND_HALF_UP).setScale(2);
//        System.out.println(bigDecimal);

    }

}
